package practice.design;

//饿汉模式
public class Singleton {
    static int anInt =2;
    private static Singleton singleton  = new Singleton();
    private Singleton(){}
    public static Singleton getSingleton(){
        return singleton;
    }


    public static void main(String[] args) {
        Singleton2 singleton2 = Singleton2.getSingleton2();
        Singleton2 singleton3 = Singleton2.getSingleton2();
        System.out.println(singleton2==singleton3); //true

        Class c = null;
        try {
            c = Class.forName("practice.design.Singleton");
            Singleton singleton = (Singleton) c.newInstance();
            Singleton singleton1 = Singleton.getSingleton();
            System.out.println(singleton == singleton1); //false
        } catch (Exception e) {
        }


    }
}

//懒汉模式  为非线程安全 所以要加上线程锁保证安全
class Singleton1 {
    private static Singleton1 singleton1;
    private Singleton1(){}
    public static synchronized Singleton1 getSingleton1(){
        if (singleton1 == null){
            singleton1 = new Singleton1();
        }
        return singleton1;
    }
}

//懒汉模式
//双重校验锁 安全且在多线程情况下能保持高效性
class Singleton2{
    private volatile static Singleton2 singleton2;
    private Singleton2(){}
    public static Singleton2 getSingleton2(){
        if (singleton2 == null){
            synchronized (Singleton2.class){
                if (singleton2 == null){
                    singleton2 = new Singleton2();
                }
            }
        }
        return singleton2;
    }
}